import {createSlice, PayloadAction} from "@reduxjs/toolkit";
import {RootState} from "../store";

export interface ProjectInfo {
    beginDate: string,
    endDate: string,
    projectName: string,
    jobTitle: string,
    detail: string
}
export type ProjectInfoList = ProjectInfo[]
export type ProjectInfoKey = keyof ProjectInfo

export const projInitialState: ProjectInfoList = [
    {
        beginDate: '',
        endDate: '',
        projectName: '',
        jobTitle: '',
        detail: ''
    }
]

const projectInfo = createSlice({
    name: 'proj',
    initialState: projInitialState,
    reducers: {
        reInitProj: (state, action) => action.payload,
        addProjectInfoItem: (state) => {
            state.push({
                beginDate: '', endDate: '',
                projectName: '', jobTitle: '', detail: ''
            })
        },
        updateProjectInfo: (state, action: PayloadAction<{index: number, updateValue: {[p in ProjectInfoKey]?: string}} >) => {
            const { index, updateValue } = action.payload
            state[index] = {...state[index], ...updateValue}
        },
        deleteProjectInfo: (state, action: PayloadAction<{index: number}>) => {
            const { index } = action.payload
            state.splice(index, 1)
        }
    }
})

export const {
    addProjectInfoItem, updateProjectInfo, deleteProjectInfo, reInitProj
} = projectInfo.actions;

export const getProjectInfoList = (state: RootState) => state.projectInfoList

export default projectInfo.reducer
